package com.fly.demo.ui;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.core.io.ClassPathResource;

import lombok.extern.slf4j.Slf4j;

/**
 * 随机打开网址延时关闭的浏览器
 */
@Slf4j
public class OpenBrowse
{
    private static List<String> urls;
    
    /**
     * 初始化
     */
    static
    {
        try (InputStream is = new ClassPathResource("urls").getInputStream())
        {
            urls = IOUtils.readLines(is, Charset.defaultCharset());
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 随机打开网址延时关闭
     */
    public static void openThenClose()
    {
        if (SystemUtils.IS_OS_WINDOWS)
        {
            urls.stream().filter(url -> RandomUtils.nextBoolean()).forEach(OpenBrowse::open);
            try
            {
                TimeUnit.SECONDS.sleep(RandomUtils.nextInt(5, 20));
                Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
                Runtime.getRuntime().exec("taskkill /F /IM msedge.exe");
                Runtime.getRuntime().exec("taskkill /F /IM iexplorer.exe");
            }
            catch (InterruptedException | IOException e)
            {
                log.error(e.getMessage(), e);
            }
        }
    }
    
    /**
     * 打开网址
     * 
     * @param url
     */
    private static void open(String url)
    {
        try
        {
            Runtime.getRuntime().exec("cmd /c start /min " + url);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    public static void main(String[] args)
    {
        Executors.newScheduledThreadPool(2).scheduleAtFixedRate(() -> openThenClose(), 2, 10, TimeUnit.SECONDS);
    }
}
